<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import  { ElMessage,ElMessageBox } from 'element-plus'
import axios from 'axios';
import {useCounterStore} from '@/stores/counter'
const counter=useCounterStore()
//import instance from '@/axios/axioshelper'
import {useRouter} from 'vue-router'
const router=useRouter()
interface RuleForm {
  userName: string
  password: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userName: '',
  password: '',
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      axios.post('http://localhost:5044/api/User/Login',ruleForm)
      .then(res=>{
        console.log(res)
        if(res.data.isSuc)
        {
          ElMessage.success('登录成功')
          counter.userinfo=res.data.data
          window.sessionStorage.setItem("token", res.data.data.token);
          //存储Token到LocalStorage
          localStorage.setItem('token',res.data.data.token);
          localStorage.setItem('userName',ruleForm.userName)
          //从LocalStorage读取Token
          const token = localStorage.getItem('token');
          console.log(token)
          router.push('/MenuView')
        }
        else{
          ElMessage.error(res.data.msg);
        }
      })
      .catch(err=>{
        console.log(err)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>
